/*
 * mySPI.c
 *
 *  Created on: 2013.04.27.
 *      Author: Gábor
 */


#include "mySPI.h"

void ClearNsel(void){
	SI32_SPI_B_clear_nss (SI32_SPI_1);
	// Wait for NSS pin low
	while(SI32_SPI_B_get_nss_pin(SI32_SPI_1));
}

void SetNsel(void){
    // Generate NSS Rising Edge
    SI32_SPI_B_set_nss (SI32_SPI_1);
    // Wait for NSS high
    while(0 == SI32_SPI_B_get_nss_pin(SI32_SPI_1));
}

//write a byte over SPI, write it on UART too
void writeByteSPI(U8 *data_trm){
	U8 rec_onSPI;
/********************bugfix_1***************/
	   SI32_SPI_B_flush_rx_fifo(SI32_SPI_0);
	   SI32_SPI_B_flush_tx_fifo(SI32_SPI_0);


	   // Write a word to the slave, ignore data shifted in
	   SI32_SPI_B_clear_all_interrupts(SI32_SPI_0);
/**********************bugfix_1 END**********/

	myUART0_send_char(*data_trm);
	SI32_SPI_B_write_tx_fifo_u8(SI32_SPI_1,*data_trm);

/********************bugfix************** */
	   while(0 == SI32_SPI_B_is_shift_register_empty_interrupt_pending(SI32_SPI_1));
	   while (SI32_SPI_B_get_rx_fifo_count(SI32_SPI_1) < 1);

	   SI32_SPI_B_flush_rx_fifo(SI32_SPI_1);
	   rec_onSPI = SI32_SPI_B_read_rx_fifo_u8(SI32_SPI_1);
/********************bugfix END************** */

//safety waiting...
for(int i = 0;i<2000;i++);
}

void SpiReadData(U8 byteCount, U8* pData){
	U8 SpireadI;
	for(SpireadI = 0; SpireadI<byteCount; SpireadI++)
	{
		SI32_SPI_B_write_tx_fifo_u8(SI32_SPI_1,0xFF);
		while (SI32_SPI_B_get_rx_fifo_count(SI32_SPI_1) < 1);
		pData[SpireadI] = SI32_SPI_B_read_rx_fifo_u8(SI32_SPI_1);
	}
}

void SpiWriteData(U8 biDataOutLength, U8 *pabiDataIn){
	U8 bCnt;
	U8 bytetosend;
	for(bCnt=0;bCnt<biDataOutLength; bCnt++){
		bytetosend = pabiDataIn[bCnt];
		writeByteSPI(&bytetosend);
	}
}

/***************** Only for example***********************
void vSpi_WriteDataSpi1(U8 biDataInLength, U8 *pabiDataIn)
{
  SEGMENT_VARIABLE(bCnt, U8, SEG_XDATA);

#ifdef SILABS_MCU_F960
  #warning Check if implemenations of DMA makes a sense for SPI on F960!
#endif

  for (bCnt=0; bCnt<biDataInLength; bCnt++)    // Send input data array via SPI
  {
    bSpi_ReadWriteSpi1(pabiDataIn[bCnt]);
  }
}*/

